/*
 * Hero.cpp
 * Any player-controllable character.
 */

#include "Hero.h"
#include <iostream>
#include <math.h>
#include <stdlib.h>

// Construct a hero. We'd better load up all our images here. 
Hero::Hero() {
	x = 20;
	y = 20;
	w = 64;
	h = 64;

	sprite_image_1 = new CL_Surface(RESOURCES_PATH "/artwork/insect1.png");
	sprite_image_2 = new CL_Surface(RESOURCES_PATH "/artwork/insect2.png");

	mouseMoveSlot = CL_Mouse::sig_move().connect(this, &Hero::mouseMovement);
	mouseClickSlot = CL_Mouse::sig_key_down().connect(this, &Hero::mouseClick);
}

// Draw this onto the CL_Display.
void Hero::paint() {
	static int 	animation = 0;
	CL_Surface 	*surface;

	int ALL_FRAMES =	12;

	if(animation > ALL_FRAMES)
		animation = 0;
	else
		animation++;
	
	if(animation > (ALL_FRAMES / 2)) {
		surface = sprite_image_1;
		moveHero();
	} else {
		surface = sprite_image_2;
	}

	// If we're looking left, turn left.
	CL_Rectf src(0, 0, 64, 64);
	CL_Rectf dest(x, y, x + 64, y + 64);

	if(!look_left) {
		src.left = 64;
		src.right = 0;
	}

	// Draw us on. 
	surface->draw_subpixel(src, dest);
}

// Just for kicks, we'll make the hero chase the mouse.
void Hero::moveHero() {
	CL_Point	hero_pos(x, y);
	CL_Point	mouse_pos(CL_Mouse::get_x(), CL_Mouse::get_y());

	// Location of the insect's mouth.
	if(look_left) {
		hero_pos 	+= CL_Point(14, 32);
	} else {
		// Flip the x coordinate on the *other* side.
		hero_pos 	+= CL_Point(64 - 14, 32);
	}

	CL_Point	delta = (hero_pos - mouse_pos);

	if(delta.x < -w/2)
		look_left = 0;
	else if(delta.x > w/2)
		look_left = 1;

	int speed_x = Hero::speed_x;
	int speed_y = Hero::speed_y;

	if(time(NULL) - last_whistle < 1) {
		speed_x *= 2;
		speed_y *= 2;
	}

	int 		deltax = -(delta.x / speed_x);
	int		deltay = -(delta.y / speed_y);

	// Limit speed to speed limits
	if(deltax < -speed_x)	deltax = -speed_x;
	if(deltax > +speed_x)	deltax = +speed_x;
	if(deltay < -speed_y)	deltay = -speed_y;
	if(deltay > +speed_y)	deltay = +speed_y;

	// Just for kicks, jump a random value up or down.
	int rnd = ((float) rand() / RAND_MAX) * speed_x - ((float)speed_x / 2);

	x += deltax + rnd;

	rnd = ((float) rand() / RAND_MAX) * speed_y - ((float)speed_y / 2);
	y += deltay + rnd;
}

void Hero::mouseMovement(const CL_InputEvent &evt) {
}

void Hero::mouseClick(const CL_InputEvent &evt) {
	// Double-click.
	if(evt.repeat_count >= 1 && time(NULL) - last_whistle > 1) {
		last_whistle = time(NULL);
	}
}

// Destroy this world.
Hero::~Hero() {
	delete sprite_image_1;
	delete sprite_image_2; 
}
